<?php
	class EditorsController extends  AppController{
		var $name = 'Editors';
		var $components = array('Auth','Cookie','Session');
		
		/**
		 * 
		 * The method is for editor to feature the post.
		 * @param unknown_type $postId
		 */
		function feature($postId = null){
			if(!empty($postId)){
				$cookie = $this->Cookie->read('Auth.User');
				$userId = $cookie['id'];
				$userPermission = $cookie['permission'];
				if($userPermission == 'editor'){
					$this->loadModel('Editor');
					// find the tag of the editor .
					$editortag = $this->Editor->find('first',array(
							'conditions'=>array('Editor.users_id'=>$cookie['id']),
							'fields'=>array('Tag.name','Tag.id') ));
					// if the user is a editor ...he can feature post.
					$this->loadModel('EditorFeaturePost');
					$tmp = $this->EditorFeaturePost->find('first',array(
						'conditions'=>array('EditorFeaturePost.users_id'=>$cookie['id'],'EditorFeaturePost.posts_id'=>$postId ),
						'fields'=>array('EditorFeaturePost.users_id')
					));
					if(!empty($tmp)){
						// if he feature the post already ,he can't feature again.
						$this->Session->setFlash('You have featured current Post aready!');
						return 'You have featured current Post aready';
					}else{
						// if he doesn't feature the post ,save the feature info .
						$saveInfo = $this->EditorFeaturePost->save(array(
							'EditorFeaturePost'=>array(
								'users_id'=>$cookie['id'],
								'posts_id'=>$postId,
								'tagname' =>$editortag['Tag']['name']
							)));
						// return the save informations.
						if($saveInfo){
							$this->loadModel('PostHasTag');
							$this->PostHasTag->unbindModel(array('belongsTo'=>array( 'Post')));
							// find whether post has the current tag.
							$result = $this->PostHasTag->find('first',array(
									'conditions'=>array('PostHasTag.tags_id'=>$editortag['Tag']['id'],'PostHasTag.posts_id'=>$postId),
									'fields'=>'PostHasTag.id'
									)
							);
							// if the post has no this tag ,add it.
							if(empty($result)){
								$this->loadModel('PostHasTag');
								$this->PostHasTag->unbindModel(array('belongsTo'=>array('Post','Tag')));
								$tmp = $this->PostHasTag->save(array(
										'PostHasTag'=>array(
											'posts_id'=>$postId,
											'tags_id'=>$editortag['Tag']['id']
										)
								));
							}
							$this->Session->setFlash('Success!');
							return 'Success';
						}else{
							$this->Session->setFlash('failed');
							return 'failed' ;
						}
					}
				}
			}
		}		
	}
?>